package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.UserEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpConfig.WebPage;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.utils.StringHelper;
import com.umeng.analytics.MobclickAgent;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * @author: yusonglin
 * @类 说 明:
 * @version 1.0
 * @创建时间：2015年7月24日 下午2:30:05
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	public static final String TAG_IS_CAN_NOT_BACK = "TAG_IS_CAN_NOT_BACK";// 标记是否可以回退

	private EditText mPhoneEdit;
	private EditText mInvestCodeEdit;
	private EditText mAuthcodeEdit;
	private Button mAuthcodeButton;
	private Button mNextButton;
	private LinearLayout layoutLoginInvest;

	private CheckBox mAgreementCb;
	private TextView mAgreementText;

	protected boolean isgetCode = false;

	private String phone;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		AccountManager.logout(this);
		initView();
		setUpView();
		initListeners();
	}

	private void initListeners() {
		mPhoneEdit.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.toString().length() == 11) {
					if ("".equals(SharedPreferencesHelper.getString(s.toString(), ""))) {
						layoutLoginInvest.setVisibility(View.VISIBLE);
					}
				} else {
					layoutLoginInvest.setVisibility(View.GONE);
				}
			}

		});
	}

	private void initView() {
		mPhoneEdit = (EditText) this.findViewById(R.id.edittext_phone);
		mInvestCodeEdit = (EditText) this.findViewById(R.id.edittext_invest_code);
		mAuthcodeEdit = (EditText) this.findViewById(R.id.edittext_authcode);
		mAuthcodeButton = (Button) this.findViewById(R.id.button_authcode);
		mNextButton = (Button) this.findViewById(R.id.button_next);
		mAgreementCb = (CheckBox) this.findViewById(R.id.cb_agreement);
		mAgreementText = (TextView) this.findViewById(R.id.textview_agreement);
		layoutLoginInvest = (LinearLayout) this.findViewById(R.id.layout_login_invest);
	}

	private void setUpView() {
		Intent intent = getIntent();
		if (!intent.getBooleanExtra(TAG_IS_CAN_NOT_BACK, false)) {
		}

		mAuthcodeButton.setOnClickListener(this);
		mNextButton.setOnClickListener(this);
		mAgreementText.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_agreement:
			Intent intent = new Intent(this, WebBrowserActivity.class);
			intent.putExtra(WebBrowserActivity.TITLE, "注册协议");
			intent.putExtra(WebBrowserActivity.URL, WebPage.REGISTER_AGREEMENT);
			startActivity(intent);
			break;
		case R.id.button_authcode:
			getAuthcode();
			break;
		case R.id.button_next:
			phone = mPhoneEdit.getText().toString().trim();
			String authcode = mAuthcodeEdit.getText().toString().trim();
			String investCode = mInvestCodeEdit.getText().toString().trim();
			if (TextUtils.isEmpty(phone) || !StringHelper.isPhoneNumber(phone)) {
				showToast("请输入合格的手机号");
				return;
			}
			if (TextUtils.isEmpty(authcode)) {
				showToast("请输入您收到的验证码");
				return;
			}

			if (!mAgreementCb.isChecked()) {
				showToast("请同意服务协议");
				return;
			}

			startLoadingDialog();
			RequestService.getInstance().login(this, phone, authcode, investCode, UserEntity.class,
					new RequestListener() {

						@Override
						public void onSuccess(int requestCode, BaseEntity resultData) {
							dismissLoadingDialog();
							if (resultData.isOk()) {

								UserEntity user = (UserEntity) resultData;
								AccountManager.saveAccount(user);
								getUserInfo();
								SharedPreferencesHelper.setBoolean(LoginActivity.this,
										SharedPreferencesHelper.Field.IS_COME_BACK, true);
								// 记录该手机在本地使用过
								SharedPreferencesHelper.setString(phone, phone);

								startActivity(new Intent(LoginActivity.this, SelectDisplayActivity.class));
								finish();
							} else {
								showToast(resultData.getMsg());
							}
						}

						@Override
						public void onFailed(int requestCode, Exception error, String msg) {
							dismissLoadingDialog();
							showToast(R.string.please_check_network);
						}
					});
//                 new Gson().fromJson()
			break;
		}
	}

	private void getUserInfo() {
		startLoadingDialog();


		RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {
					UserInfoEntity entity = (UserInfoEntity) resultData;
					
					AccountManager.saveUserInfo(entity.getData());
					//登录IM
					IMFactory.logout();
					IMFactory.login(IMFactory.getImId(entity.getData().getUserid()), IMFactory.default_password, null);
					JPushInterface.setAlias(LoginActivity.this, entity.getData().getBaseinfo().getMobile(),
							new TagAliasCallback() {
						@Override
						public void gotResult(int arg0, String arg1, Set<String> arg2) {
						}
					});
					JPushInterface.init(LoginActivity.this); // 初始化 JPush
                    MobclickAgent.onProfileSignIn(AccountManager.getUserId());
				} else {
					showToast(resultData.getMsg());
				}
			}
			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    private void getAuthcode() {

		String phone = mPhoneEdit.getText().toString().trim();
		if (TextUtils.isEmpty(phone) || !StringHelper.isPhoneNumber(phone)) {
			showToast("请输入合格的手机号");
			return;
		}

		startLoadingDialog();
		RequestService.getInstance().sendLoginSms(this, phone, BaseEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {
				dismissLoadingDialog();
				if (resultData.isOk()) {

					isgetCode = true;

					mAuthcodeButton.setEnabled(false);
					mHandler.removeMessages(0);
					mHandler.sendMessageDelayed(mHandler.obtainMessage(0), 1 * 1000);

					showToast("验证码已发送");
				} else {
					showToast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				dismissLoadingDialog();
				showToast(R.string.please_check_network);
			}
		});
	}

	private static final int DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME = 60;
	private int mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				--mUpdateCount;
				if (mUpdateCount > 0) {
					mAuthcodeButton.setText(String.format("重新发送(%d)", mUpdateCount));
					sendMessageDelayed(obtainMessage(0), 1 * 1000);
					mAuthcodeButton.setEnabled(false);
				} else {
					mAuthcodeButton.setText("重新发送");
					mUpdateCount = DEFAULT_SMS_VERIFYCODE_COUNTDOWN_TIME;
					mAuthcodeButton.setEnabled(true);
				}
			}
		}
	};

}
